﻿/*
 *  ChgDoc CMS - GNU General Public License, version 3 (GPL-3.0)
 *  Copyright (C)  2012. Ian Quigley
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace ChgDoc.Edit
{
    [AdminPage( "Edit File", "Admin" )]
    public partial class FileTextEdit : BasePage
    {
        protected void Page_Load( object sender, EventArgs e )
        {
            if (IsPostBack || string.IsNullOrEmpty(Request.QueryString["file"]))
                return;

            FileInfo fi = new FileInfo( Path.Combine( Config.UploadFolder, Request.QueryString["file"] ) );
            if (!fi.Exists)
                return;

            txtTitle.Text = Request.QueryString["file"];

            using (StreamReader reader = new StreamReader( fi.FullName ))
                txtBody.Text = reader.ReadToEnd();

            switch (Param("mode"))
            {
                case "css":
                    litHeader.Text = "<script type=\"text/javascript\" src=\"content/codemirror/mode/css/css.js\"></script> ";
                    litCodeMirror.Text = string.Format(CodeMirror, "css", "cssHint");
                    break;
                
                case "js":
                    litHeader.Text = "<script type=\"text/javascript\" src=\"content/codemirror/util/javascript-hint.js\"></script> " + 
                                     "<script type=\"text/javascript\" src=\"content/codemirror/mode/javascript/javascript.js\"></script> ";

                    litCodeMirror.Text = string.Format(CodeMirror, "javascript", "javascriptHint");
                    break;
            }
        }

        protected void btnSave_click( object sender, EventArgs e )
        {
            using (StreamWriter writer = new StreamWriter( Path.Combine( Config.UploadFolder, Request.QueryString["file"] ) ))
            {
                writer.Write( txtBody.Text );
            }

            DoReturnUrl();
      

        }
    

    private  string CodeMirror = 
    "<script type=\"text/javascript\">" + 
    "var myCodeMirror = CodeMirror.fromTextArea( $('#pageContent_txtBody').get(0), {{ theme: 'customized', mode: '{0}', extraKeys: {{ \"Ctrl-Space\": function (cm) {{ CodeMirror.simpleHint(cm, CodeMirror.{1}); }} }} }}); " + 
    "</script>";
    }
}